<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <a-descriptions title="项目信息">
        <a-descriptions-item label="投票项目">
          {{ project.projectName }}
        </a-descriptions-item>
        <a-descriptions-item label="投票类型">
          {{ voteType[project.projectType] }}
        </a-descriptions-item>
        <a-descriptions-item label="限投数">
          {{ project.maxVote }}
        </a-descriptions-item>
        <a-descriptions-item label="发起人">
          {{ project.sponsor }}
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="project.state | selectColorFilter1">{{ project.state | selectTextFilter1 }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="是/否已投票">
          <a-tag :color="project.voted | selectColorFilter">{{ project.voted | selectTextFilter }}</a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="日期">
          {{ project.date }}
        </a-descriptions-item>
      </a-descriptions>
      <a-row>
        <div style="display: flex;align-items: center;justify-content: space-between;flex-direction: row;">
          <div></div>
          <div>
            <a-button type="primary" style="margin-left: 10px" @click="goBack">返回</a-button>
          </div>
        </div>
      </a-row>
    </a-card>

    <a-card
      style="margin-top: 24px"
      :bordered="false"
      title="候选人列表">
      <div style="display: flex;width: 100%" v-if="project.projectType === 1">
        <div style="margin-bottom: 8px;margin-left: auto;font-size: 20px">
          <span>您还可以投 </span>
          <a-tag v-if="left > 0" style="font-size: 20px">{{ left }}</a-tag>
          <a-tag v-else color="red" style="font-size: 20px">{{ left }}</a-tag>
          <span>张同意票</span>
        </div>
      </div>
      <a-table :data-source="candidates"
               :columns="columns[project.projectType]"
               size="middle"
               :pagination="{ pageSize: 20 }"
      >
        <span slot="fileAddr" slot-scope="text, record">
          <a @click="handleFiles(record)">附件查看</a>
        </span>
        <template slot="subLevel" slot-scope="text, record">
          <span slot="subLevel">
            <a-select default-value="请选择" style="width: 100px" v-model="record.subLevel" :disabled="submitDisabled">
              <a-select-option v-for="subLevel in subLevels" :key="subLevel" >
                {{ subLevel }}
              </a-select-option>
            </a-select>
          </span>
        </template>
        <template slot="workLevel" slot-scope="text, record">
          <span slot="workLevel">
            <a-select default-value="请选择" style="width: 100px" v-model="record.workLevel" :disabled="submitDisabled">
              <a-select-option v-for="workLevel in workLevels" :key="workLevel" >
                {{ workLevel }}
              </a-select-option>
            </a-select>
          </span>
        </template>
        <template slot="agree" slot-scope="text, record">
          <a-radio-group
            v-model="record.agree"
            :disabled="submitDisabled"
            @change="onchange(record)">
            <a-radio :value="0" :disabled="left === 0">
              同意
            </a-radio>
            <a-radio :value="1">
              不同意
            </a-radio>
            <a-radio :value="2">
              弃权
            </a-radio>
          </a-radio-group>
        </template>
      </a-table>
      <div style="text-align: center">
        <a-button type="primary" block style="width: 300px" @click="submit" :disabled="submitDisabled">
          提交
        </a-button>
      </div>
    </a-card>
    <DownloadFiles ref="downLoadFiles"></DownloadFiles>
  </page-header-wrapper>
</template>

<script>
// 演示如何使用 this.$dialog 封装 modal 组件
// import TaskForm from './modules/TaskForm'
import Info from './components/Info'
import { queryCandidateByProject } from '@/api/vote/candidate'
import { STable } from '@/components'
import { addVote, queryVoteResult } from '@/api/vote/vote'
import DownloadFiles from '../manage/modules/DownloadFiles'
import { Modal } from 'ant-design-vue'

let that

export default {
  name: 'StandardList',
  components: {
    STable,
    // TaskForm,
    Info,
    DownloadFiles
  },
  data () {
    return {
      left: 0,
      submitDisabled: false,
      pd: [],
      candidates: [],
      status: 'all',
      stateMap: ['未开始', '进行中', '已结束'],
      project: [],
      workLevels: ['国际领先', '国际先进', '国内领先', '国内先进', '国内一般', '其它水平'],
      subLevels: ['完全达到', '基本达到', '略有差距', '差距较大'],
      voteType: ['选择评价型', '同意反对型'],
      // 表头
      columns: [
        [
          {
            title: '姓名',
            dataIndex: 'candidateName',
            key: 'candidateName',
            align: 'center'
          },
          {
            title: '单位',
            dataIndex: 'dept',
            align: 'center'
          },
          {
            title: '职工号',
            dataIndex: 'employeeNumber',
            align: 'center'
          },
          {
            title: '身份证号',
            dataIndex: 'idNumber',
            align: 'center'
          },
          {
            title: '研究工作水平',
            dataIndex: 'workLevel',
            align: 'center',
            width: '300px',
            scopedSlots: { customRender: 'workLevel' }
          },
          {
            title: '专业技术职务水平',
            dataIndex: 'subLevel',
            align: 'center',
            width: '240px',
            scopedSlots: { customRender: 'subLevel' }
          },
          {
            title: '附件',
            dataIndex: 'fileAddr',
            align: 'center',
            scopedSlots: { customRender: 'fileAddr' }
          }
        ],
        [
          {
            title: '姓名',
            dataIndex: 'candidateName',
            key: 'candidateName',
            align: 'center'
          },
          {
            title: '单位',
            dataIndex: 'dept',
            align: 'center'
          },
          {
            title: '职工号',
            dataIndex: 'employeeNumber',
            align: 'center'
          },
          {
            title: '身份证号',
            dataIndex: 'idNumber',
            align: 'center'
          },
          {
            title: '投票',
            dataIndex: 'agree',
            align: 'center',
            width: '300px',
            scopedSlots: { customRender: 'agree' }
          },
          {
            title: '附件',
            dataIndex: 'fileAddr',
            align: 'center',
            scopedSlots: { customRender: 'fileAddr' }
          }
        ]
      ],
      record: [],
      // selectedRowKeys: [],
      // selectedRows: [],
      queryParam: {},
      // custom table alert & rowSelection
      // options: {
      //   alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
      //   rowSelection: {
      //     selectedRowKeys: this.selectedRowKeys,
      //     onChange: this.onSelectChange
      //   }
      // },
      optionAlertShow: false
    }
  },
  beforeCreate() {
    that = this
  },
  created () {
    // this.tableOption()
    this.listCandidate()
  },
  filters: {
    selectTextFilter (val) {
      let name = ''
      if (val === 1) {
        name = '已投票'
      } else {
        name = '开始投票'
      }
      return name
    },
    selectColorFilter (val) {
      let name = ''
      if (val === 1) {
        name = 'green'
      } else {
        name = 'red'
      }
      return name
    },
    selectTextFilter1(val) {
      let name = ''
      if (val === 0) {
        name = '未开始'
      } else if (val === 1) {
        name = '投票中'
      } else {
        name = '已结束'
      }
      return name
    },
    selectColorFilter1(val) {
      let name = ''
      if (val === 0) {
        name = 'blue'
      } else if (val === 1) {
        name = 'green'
      } else {
        name = 'red'
      }
      return name
    },
  },
  methods: {
    // tableOption () {
    //   if (!this.optionAlertShow) {
    //     this.options = {
    //       alert: { show: true, clear: () => { this.selectedRowKeys = [] } },
    //       rowSelection: {
    //         selectedRowKeys: this.selectedRowKeys,
    //         onChange: this.onSelectChange
    //       }
    //     }
    //     this.optionAlertShow = true
    //   } else {
    //     this.options = {
    //       alert: false,
    //       rowSelection: null
    //     }
    //     this.optionAlertShow = false
    //   }
    // },
    onchange (record) {
      if (record.pd === false && record.agree === 0) {
        if (this.left === 0) {
          record.agree = 2
          Modal.error({
            title: this.$t('提示'),
            content: this.$t('同意票数已经用完！')
          })
        } else {
          this.left--
          record.pd = true
        }
      } else if (record.pd === true && record.agree !== 0) {
        this.left++
        record.pd = false
      }
    },
    submit () {
      let flag = false
      let pd = false
      let sum = 0
      if (that.project.projectType === 0) {
        for (let i = 0; i < that.candidates.length; i++) {
          const data = that.candidates[i]
          console.log('data:', data)
          if (data.subLevel === null || data.workLevel === null) {
            flag = true
            break
          }
        }
      } else if (that.project.projectType === 1) {
        for (let i = 0; i < that.candidates.length; i++) {
          const data = that.candidates[i]
          if (data.agree === 0) sum++
          if (data.agree === null) {
            flag = true
            break
          }
        }
        if (sum > that.project.maxVote) {
          pd = true
        }
      }
      if (flag) {
        this.$message.error('投票信息不完整，请检查！')
        flag = false
      } else {
        if (pd) {
          this.$message.error('同意票数超过限投数，请检查！')
          flag = false
          pd = false
        } else {
          const that = this
          this.$confirm({
            title: '提交',
            content: '确定要提交吗?',
            onOk () {
              that.submitDisabled = true
              addVote(that.candidates).then(res => {
                if (res.message === 'error') {
                  that.$message.error('投票失败')
                  that.submitDisabled = false
                } else {
                  that.$message.success('投票成功')
                  that.goBack()
                }
              })
            },
            onCancel () {
            }
          })
        }
      }
    },
    goBack() {
      this.$emit('backProject')
    },
    handleFiles(record) {
      this.$refs.downLoadFiles.downLoad(record)
    },
    handleChange(value) {
      // console.log(`${value}`)
      // console.log(this.candidates)
    },
    listCandidate () {
      this.$nextTick().then(function () {
        const queryJson = {
          'pageNo': 1,
          'pageSize': 1000,
          'queryParam': JSON.stringify(that.queryParam) }
          if (that.submitDisabled) {
            queryVoteResult(queryJson)
            .then(res => {
              console.log(res.result.data)
              if (res.message !== 'error') {
                that.candidates = res.result.data
              } else {
                that.$message.error('操作失败!')
              }
            })
          } else {
            queryCandidateByProject(queryJson)
              .then(res => {
                if (res.message !== 'error') {
                  // that.candidates = res.result.data
                  for (let i = 0; i < res.result.data.length; i++) {
                    that.candidates.push(res.result.data[i])
                    that.candidates[i].pd = false
                    if (that.project.projectType > 0) {
                      that.candidates[i].agree = 2
                    }
                  }
                } else {
                  that.$message.error('操作失败！')
                }
              })
          }
       })
    },
    handleOk () {
      this.$refs.table.clearSelected()
      this.$refs.table.refresh(false)
    },
    // onSelectChange (selectedRowKeys, selectedRows) {
    //   this.selectedRowKeys = selectedRowKeys
    //   this.selectedRows = selectedRows
    // },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    edit (record, voted) {
      this.project = record
      this.left = this.project.maxVote
      this.submitDisabled = voted
      this.queryParam.projectId = this.project.projectId
    },
    onSearch () {
      this.$refs.table.refresh(true)
    }
  }
}
</script>

<style lang="less" scoped>
.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}

.list-content-item {
  color: rgba(0, 0, 0, .45);
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  margin-left: 40px;
  span {
    line-height: 20px;
  }
  p {
    margin-top: 4px;
    margin-bottom: 0;
    line-height: 22px;
  }
}
</style>
